package com.gzgy.ustore.api.web.handler;

import com.gzgy.ustore.api.common.exception.BaseAPIException;
import com.gzgy.ustore.api.common.util.*;
import com.gzgy.ustore.api.service.ApkService;
import com.gzgy.ustore.api.service.PdaMgrService;
import com.gzgy.ustore.api.util.ApkUtil;
import com.gzgy.ustore.api.util.IconUtil;
import com.gzgy.ustore.api.model.ApkInfo;
import com.gzgy.ustore.api.util.ResultUtil;
import com.gzgy.ustore.api.web.view.ApkFileRecordView;
import com.ustore.model.ApkFileRecord;
import com.ustore.model.PdaMgr;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Map;

/**
 * Created by yimi on 2017/7/10.
 */
public class ApkUploadHandler {

    private final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private ApkService apkService;

    @Autowired
    private PdaMgrService pdaMgrService;

    @Value("${apk.upload.path}")
    private String APK_UPLOAD_PATH;

    @Value("${upload.temp.path}")
    private String UPLOAD_TEMP_PATH;


    public String uploadApk(MultipartFile file, String userId, String companyId, String appCode) throws Exception {
        String apkFileName = Constant.getUUID() + ".apk";
        String imageFileName = Constant.getUUID() + ".png";
        //上传apk到服务器临时文件上
        File tempFile = new File(UPLOAD_TEMP_PATH, apkFileName);
        FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
        //解析apk
        String apkTempPath = UPLOAD_TEMP_PATH + apkFileName;
        ApkInfo apkInfo = new ApkUtil().getApkInfo(apkTempPath);
        //app相对路径
        String appPath = companyId + "/" + apkInfo.getPackageName() + "/" + apkInfo.getVersionCode() + "/";
        //app真实路径
        String appMkdir = APK_UPLOAD_PATH + appPath;
        //写入apk到真实目录 并且 删除 临时 文件
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(appMkdir, apkFileName));
        tempFile.delete();
        // 获取Icon并保存到指定位置
        IconUtil.extractFileFromApk(appMkdir + apkFileName, apkInfo.getApplicationIcon(), appMkdir + imageFileName);
        //获取file 大小 单位 bytes 转 mb 1048576
        Double size = NumberUtils.toDouble(Long.toString(file.getSize())) / 1048576d;
        //文件大小保留两位小数
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        size = NumberUtils.toDouble(nf.format(size));
        //apk具体位置（相对路径）
        String apkPath = appPath + apkFileName;
        //logo具体位置（相对路径）
        String imagePath = appPath + imageFileName;

        ApkFileRecord fileRecord = apkService.apkUpload(apkPath, imagePath, size, apkInfo, userId, companyId, appCode);

        ApkFileRecordView view = new ApkFileRecordView(fileRecord);

        return ResultUtil.getResultJson(view);
    }


    public String quickRegisterDevice(String dp) throws UnsupportedEncodingException {

        Map<String, String> map = ParamUtil.paramToMap(dp);
        String sn = map.get("sn");
        Assert.hasText(sn,"p_data :" +I18nUtil.getMessage(-2,null,"zh_CN"));

        //对扫描二维码内容进行解密
        String wp = map.get("wp");
        logger.info("before: "+wp);
        wp = URLDecoder.decode(wp, "UTF-8");
        logger.info("after : " +wp);
        String dwp = EncryptionUtils.decryptAES(wp, EncryptionUtils.KEY, EncryptionUtils.IV);
        if (dwp == null) {
            logger.info("解密失败，解密字符串【" + wp + "】");
            throw new BaseAPIException(I18nUtil.getMessage(-1, null, "zh_CN"));
        }
        //get data
        Map<String, String> webData = ParamUtil.paramToMap(dwp);

        String deviceToken = webData.get("deviceToken");

        String companyId = webData.get("companyId");
        Assert.hasText(companyId,"p_data :" +I18nUtil.getMessage(-2,null,"zh_CN"));
        String dvcType = webData.get("dvcType");
        Assert.hasText(dvcType,"p_data :" +I18nUtil.getMessage(-2,null,"zh_CN"));
        String userId = webData.get("userId");
        Assert.hasText(userId,"p_data :" +I18nUtil.getMessage(-2,null,"zh_CN"));
        String orgTreeId = webData.get("orgTreeId");
        Assert.hasText(orgTreeId,"p_data :" +I18nUtil.getMessage(-2,null,"zh_CN"));
        String dvcGroupId = webData.get("dvcGroupId");
        Assert.hasText(dvcGroupId,"p_data :" +I18nUtil.getMessage(-2,null,"zh_CN"));
        String status = webData.get("status");
        Assert.hasText(status,"p_data :" +I18nUtil.getMessage(-2,null,"zh_CN"));
        String remark = webData.get("remark");
        String orgName = webData.get("orgName");
        Assert.hasText(orgName,"p_data :" +I18nUtil.getMessage(-2,null,"zh_CN"));

        PdaMgr pdaMgr = new PdaMgr() ;
        pdaMgr.setOrgTreeId(orgTreeId);
        pdaMgr.setDvcToken(deviceToken);
        pdaMgr.setDvcId(sn);
        pdaMgr.setStatus(NumberUtils.toInt(status));
        pdaMgr.setRemark(remark);
        pdaMgr.setOrgName(orgName);
        pdaMgr.setDvcType(dvcType);
        pdaMgr.setDvcGroupId(dvcGroupId);
        pdaMgr.setCompanyId(NumberUtils.toInt(companyId));
        pdaMgr.setCreatedTime(DateUtil.getCurrentDate());
        pdaMgr.setCreatedBy(userId);

        return pdaMgrService.registerPda(pdaMgr);
    }

}

